#include "download.h"
#include "ui_download.h"
#include <QDir>
#include <QMessageBox>
#include <QDesktopServices>

Download::Download(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Download)
{
    ui->setupUi(this);
    setWindowTitle("下载");
    QString curPath=QDir::currentPath();
    QDir dir(curPath);
    QString sub="temp";
    dir.mkdir(sub);
    ui->editPath->setText(curPath+"/"+sub+"/");
}

Download::~Download()
{
    delete ui;
}

void Download::on_finishedA()
{
    QFileInfo fileInfo;
    fileInfo.setFile(downloadFile->fileName());
    downloadFile->close();
    delete downloadFile;
    downloadFile=Q_NULLPTR;
    reply->deleteLater();
    reply=Q_NULLPTR;
    if(ui->checkBox->isCheckable())
    {
        QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absolutePath()));
        ui->btnDownload->setEnabled(true);
    }
}

void Download::on_readtReadA()
{
    downloadFile->write(reply->readAll());
}

void Download::on_downloadProgressA(qint64 bytesRead, qint64 totalBytes)
{
    ui->progressBar->setMaximum(totalBytes);
    ui->progressBar->setValue(bytesRead);
}

void Download::on_pushButton_2_clicked()
{

}

void Download::on_btnDownload_clicked()
{
    QString urlSpec=ui->editUrl->text().trimmed();
    if(urlSpec.isEmpty())
    {
        QMessageBox::information(this,"error","请输入正确的URL地址");
        return;
    }
    QUrl newUrl=QUrl::fromUserInput(urlSpec);
    if(!newUrl.isValid())
    {
        QMessageBox::information(this,"error",
                                 QString("无效的URL：%1 \n错误信息%2").arg(urlSpec,newUrl.errorString()));
        return;
    }

    QString tempDir=ui->editPath->text().trimmed();
    if(tempDir.isEmpty())
    {
        QMessageBox::information(this,"error","目录无效");
        return;
    }
    QString fullFileName=tempDir+newUrl.fileName();
    if(QFile::exists(fullFileName))
    {
        QFile::remove(fullFileName);
    }
    downloadFile=new QFile(fullFileName);
    if(!downloadFile->open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this,"error","临时文件打开失败");
        return;
    }
    ui->btnDownload->setEnabled(false);
    reply=networkManager.get(QNetworkRequest(newUrl));
    connect(reply,SIGNAL(finished()),this,SLOT(on_finishedA()));
    connect(reply,SIGNAL(readyRead()),this,SLOT(on_readtReadA()));
    connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(on_downloadProgressA(qint64,qint64)));
}


